package com.yanboo.modules.mnt.rest;

import com.yanboo.common.annotation.CustomController;
import com.yanboo.modules.mnt.service.DatabaseService;
import com.yanboo.modules.mnt.service.dto.DatabaseDto;
import com.yanboo.modules.mnt.service.dto.DatabaseQueryCriteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import com.yanboo.logging.annotation.Log;
import com.yanboo.common.exception.BadRequestException;
import com.yanboo.modules.mnt.domain.Database;
import com.yanboo.modules.mnt.util.SqlUtils;
import com.yanboo.common.utils.FileUtil;
import com.yanboo.common.utils.PageResult;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Set;


/**
 * 运维：数据库管理
 */
@Tag(name = "运维：数据库管理")
@CustomController
@RequiredArgsConstructor
@RequestMapping("/api/database")
public class DatabaseController {

	private final String fileSavePath = FileUtil.getTmpDirPath()+"/";
    private final DatabaseService databaseService;

	/**
	 * 导出数据库数据
	 * @param response
	 * @param criteria
	 * @throws IOException
	 */
	@Operation(summary = "导出数据库数据")
	@GetMapping(value = "/download")
	public void exportDatabase(HttpServletResponse response, DatabaseQueryCriteria criteria) throws IOException {
		databaseService.download(databaseService.queryAll(criteria), response);
	}

	/**
	 * 查询数据库
	 * @param criteria
	 * @param pageable
	 * @return
	 */
	@Operation(summary = "查询数据库")
    @GetMapping
    public ResponseEntity<PageResult<DatabaseDto>> queryDatabase(DatabaseQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(databaseService.queryAll(criteria,pageable),HttpStatus.OK);
    }

	/**
	 * 新增数据库
	 * @param resources
	 * @return
	 */
	@Operation(summary = "新增数据库")
    @Log("新增数据库")
    @PostMapping
    public ResponseEntity<Object> createDatabase(@Validated @RequestBody Database resources){
		databaseService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

	/**
	 * 修改数据库
	 * @param resources
	 * @return
	 */
	@Operation(summary = "修改数据库")
    @Log("修改数据库")
    @PutMapping
    public ResponseEntity<Object> updateDatabase(@Validated @RequestBody Database resources){
        databaseService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

	/**
	 * 删除数据库
	 * @param ids
	 * @return
	 */
	@Operation(summary = "删除数据库")
    @Log("删除数据库")
    @DeleteMapping
    public ResponseEntity<Object> deleteDatabase(@RequestBody Set<Long> ids){
        databaseService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

	/**
	 * 测试数据库链接
	 * @param resources
	 * @return
	 */
	@Operation(summary = "测试数据库链接")
	@Log("测试数据库链接")
	@PostMapping("/testConnect")
	public ResponseEntity<Object> testConnect(@Validated @RequestBody Database resources){
		return new ResponseEntity<>(databaseService.testConnection(resources),HttpStatus.CREATED);
	}

	/**
	 * 执行SQL脚本
	 * @param file
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Operation(summary = "执行SQL脚本")
	@Log("执行SQL脚本")
	@PostMapping(value = "/upload")
	public ResponseEntity<Object> uploadDatabase(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{
		String id = request.getParameter("id");
		DatabaseDto database = databaseService.findById(Long.parseLong(id));
		String fileName;
		if(database != null){
			fileName = file.getOriginalFilename();
			File executeFile = new File(fileSavePath+fileName);
			FileUtil.del(executeFile);
			file.transferTo(executeFile);
			String result = SqlUtils.executeFile(database.getJdbcUrl(), database.getUserName(), database.getPwd(), executeFile);
			return new ResponseEntity<>(result,HttpStatus.OK);
		}else{
			throw new BadRequestException("Database not exist");
		}
	}
}
